/*
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                   O\  =  /O
 *                ____/`- -'\____
 *              .'  \\|     |//  `.
 *             /  \\|||  :  |||//  \
 *            /  _||||| -:- |||||-  \
 *            |   | \\\  -  /// |   |
 *            | \_|  ''\- -/''  |   |
 *            \  .-\__  `-`  ___/-. /
 *          ___`. .'  /- . -\  `. . __
 *       ."" '<  `.___\_<|>_/___.'  >'"".
 *      | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *      \  \ `-.   \_ __\ /__ _/   .-` /  /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=- -='
 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *           佛祖保佑       永无BUG
 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 */

package com.softeem.starwars.panel;

import com.softeem.starwars.entity.Aestroid;
import com.softeem.starwars.entity.Bullet;
import com.softeem.starwars.entity.Enemy;
import com.softeem.starwars.entity.Player;
import com.softeem.starwars.frame.MainFrame;
import com.softeem.starwars.sound.SoundPool;
import com.softeem.starwars.utils.HitCheckUtils;
import com.softeem.starwars.utils.ImageLoader;
import com.softeem.starwars.utils.Settings;

import javax.sound.sampled.SourceDataLine;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.TimerTask;
import java.util.Timer;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 游戏面板
 * @Author mrchai 2020/4/8 14:20
 */
public class GamePanel extends JPanel{

    private MainFrame main;
    private BufferedImage bg;
    private BufferedImage logo;
    private BufferedImage scoreBg;
    private BufferedImage timeBg;
    private int x;
    private int y;
    private Timer timer = new Timer();
    public static int time;
    public static int score;
    public static Player player = new Player();
    public static CopyOnWriteArrayList<Enemy> enemies = new CopyOnWriteArrayList<Enemy>();
    public static CopyOnWriteArrayList<Aestroid> aestroids = new CopyOnWriteArrayList<Aestroid>();
    public static CopyOnWriteArrayList<Bullet> bullets = new CopyOnWriteArrayList<Bullet>();
    private SoundPool sound;

    public GamePanel(MainFrame main){
        this.main = main;
        bg = ImageLoader.load("background.png");
        logo = ImageLoader.load("logo.png");
        scoreBg = ImageLoader.load("icon-score.png");
        timeBg = ImageLoader.load("icon-time.png");
        //背景滚动任务启动
        timer.schedule(new BgAnimation(),0,10);
        //创建敌机任务启动(延时2秒出现敌机)
        timer.schedule(new EnemyTask(),2000,Settings.ENEMY_CREATE_INTEVAL * 1000);
        //创建小行星任务启动(延时3秒出现小行星)
        timer.schedule(new AestroidTask(),3000,Settings.AESTROID_CREATE_INTEVAL * 1000);
        //计时
        timer.schedule(new TimeAddTask(),0,1000);
        //碰撞检测判断
        timer.schedule(new HitCheckTask(),0,100);
        //绑定按键事件
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                 if(e.getKeyCode() != KeyEvent.VK_SPACE){
                     //移动
                     player.move(e.getKeyCode());
                 }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_SPACE){
                    //攻击
                    player.shoot();
                }
            }
        });
        //背景音乐
        sound = new SoundPool(SoundPool.BG_MUSIC,true);
        sound.start();
    }


    /**
     * 背景滚动动画
     */
    class BgAnimation extends TimerTask {
        @Override
        public void run() {
            x--;
            if(x == (Settings.WIDTH - bg.getWidth())){
                x = 0;
            }
            repaint();
        }
    }

    /**
     * 敌机创建任务
     */
    class EnemyTask extends TimerTask{
        @Override
        public void run() {
          Enemy e = new Enemy();
          enemies.add(e);
          new Thread(e).start();
        }
    }

    /**
     * 小行星创建任务
     */
    class AestroidTask extends TimerTask{
        @Override
        public void run() {
            Aestroid a = new Aestroid();
            aestroids.add(a);
            new Thread(a).start();
        }
    }

    /**
     * 计时任务
     */
    class TimeAddTask extends TimerTask{

        @Override
        public void run() {
            time++;
        }
    }

    /**
     * 玩家碰撞检测
     */
    class HitCheckTask extends TimerTask{
        @Override
        public void run() {

            enemies.forEach(e->{
                // 判断是否与玩家产生碰撞
                if(HitCheckUtils.isHit(e.getX(),e.getY(),e.getWidth(),e.getHeight(),player.getX(),player.getY(),player.getWidth(),player.getHeight())){
                    player.destroy();
                    new SoundPool(SoundPool.BOOM,false).start();
                    over();
                    return;
                }
            });


            aestroids.forEach(a->{
                // 判断是否与玩家产生碰撞
                if(HitCheckUtils.isHit(a.getX(),a.getY(),a.getWidth(),a.getHeight(),player.getX(),player.getY(),player.getWidth(),player.getHeight())){
                    player.destroy();
                    new SoundPool(SoundPool.BOOM,false).start();
                    over();
                    return;
                }
            });

        }
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        /*背景绘制*/
        g.drawImage(bg,x,y,bg.getWidth(),bg.getHeight(),null);
        /*玩家绘制*/
        player.draw(g);
        /*UFO绘制*/
        enemies.forEach(e->e.draw(g));
        /*小行星绘制*/
        aestroids.forEach(a->a.draw(g));
        /*子弹绘制*/
        bullets.forEach(b-> b.draw(g));
        /**
         * 游戏面板中logo,计时,得分统计
         */
        g.drawImage(logo,10,10,logo.getWidth()/2,logo.getHeight()/2,null);
        g.drawImage(scoreBg,logo.getWidth()/2 + 10,20,scoreBg.getWidth(),scoreBg.getHeight(),null);
        g.drawImage(timeBg,logo.getWidth()/2 + scoreBg.getWidth() + 20,20,timeBg.getWidth(),timeBg.getHeight(),null);
        g.setFont(new Font("微软雅黑",Font.PLAIN,20));
        g.setColor(Color.WHITE);
        if(time > 99 || score > 99){
            g.setFont(new Font("微软雅黑",Font.PLAIN,15));
        }
        g.drawString(score+"",logo.getWidth()/2 + 42,42);
        g.drawString(time+"",logo.getWidth()/2 + scoreBg.getWidth() + 52,42);
    }

    /**
     * 游戏结束
     */
    public void over(){
        //音效关闭
        sound.close();
        //取消所有定时任务
        timer.cancel();
        //隐藏当前面板
        GamePanel.this.setVisible(false);
        EndPanel end = new EndPanel(main);
        //开启结束面板
        main.add(end);
    }
}
